package com.patelski.magic;


import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

import com.patelski.magic.model.User;
import com.patelski.magic.util.DateUtils;

@Scope(ScopeType.SESSION)
@Name("authenticator")
public class Authenticator {
	@Logger
	Log log;

	@In
	Identity identity;

	@In
	EntityManager entityManager;

	User loggedInUser;
	
	public boolean authenticate() {
		try {
			User user = (User) entityManager
					.createQuery(
							"from User where username = :username and password = :password")
					.setParameter("username", identity.getUsername())
					.setParameter("password", identity.getPassword())
					.getSingleResult();
//			if (user.isAdmin()) {
				identity.addRole("admin");
//			}
			log.info("Registered #0 #1 as the logged-in user at #2", user
					.getFirstName(), user.getLastName(), DateUtils
					.getCurrentDateTime());
			setLoggedInUser(user);
			return true;
		} catch (NoResultException ex) {
			log.info("Failed login: #0 at #1.", identity.getUsername(),
					DateUtils.getCurrentDateTime());
			return false;
		}

	}

	public User getLoggedInUser() {
		return loggedInUser;
	}

	public void setLoggedInUser(User loggedInUser) {
		this.loggedInUser = loggedInUser;
	}
	
	public boolean isLoggedIn() {
		return (null != identity);
	}

}
